package cn.jiyun.controller;

import cn.jiyun.pojo.Users;
import cn.jiyun.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @RequestMapping("/add")
    @ResponseBody
    public String add(Users users){
        usersService.add(users);
        return "redirect:/users/findAll";
    }

    @RequestMapping("/{page}")
    public String page(@PathVariable String page){
        return page;
    }

    @RequestMapping("/findAll")
    public String  findAll(Model model,HttpSession session){
        List<Users> all = usersService.findAll();
        model.addAttribute("all",all);
         if (session.getAttribute("user")!=null){
             return "show";
         }
         return "login";

    }

    @RequestMapping("/toAdd")
    public String  toAdd(HttpSession session){
        if (session.getAttribute("user")!=null){
            return "add";
        }
        return "login";

    }

    @RequestMapping("/login")
    public String getUsers(Users users, HttpSession session){
        Users user = usersService.getUsers(users);
        if (user!=null){
            session.setAttribute("user",user);
            return "redirect:/users/findAll";
        }else {
            return "login";
        }
    }
}
